const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/jwt');
const { User } = require('../models');

module.exports = {
  // 验证Access Token
  authenticate: async (req, res, next) => {
    try {
      const authHeader = req.headers['authorization'];
      const token = authHeader && authHeader.split(' ')[1];

      if (!token) return res.sendStatus(401);

      const decoded = jwt.verify(token, jwtConfig.secret, { issuer: jwtConfig.issuer });
      const user = await User.findByPk(decoded.userId);

      if (!user) return res.sendStatus(403);

      req.user = user;
      next();
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        return res.status(401).json({ message: 'Token expired', code: 'TOKEN_EXPIRED' });
      }
      return res.sendStatus(403);
    }
  },

  // 验证Refresh Token
  refreshToken: async (req, res, next) => {
    const { refreshToken } = req.body;
    if (!refreshToken) return res.sendStatus(401);

    try {
      const decoded = jwt.verify(refreshToken, jwtConfig.secret, { issuer: jwtConfig.issuer });
      const user = await User.findByPk(decoded.userId);

      if (!user || user.tokenVersion !== decoded.tokenVersion) {
        return res.sendStatus(403);
      }

      req.user = user;
      next();
    } catch (err) {
      return res.sendStatus(403);
    }
  }
};